package com.cxl.live.system.controller;

import com.cxl.live.base.BaseController;
import com.cxl.live.base.ResultModel;
import com.cxl.live.system.dto.FileRecord;
import com.cxl.live.system.service.FileRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Description: UserController
 * 用户Controller
 * @Author: ChenXueLi
 * @Date: 2018-11-10 13:05
 */
@Slf4j
@Api(tags = "文件管理")
@CrossOrigin
@RequestMapping("/file")
//@RestController
@Controller
public class FileRecordController extends BaseController{

    @Autowired private FileRecordService fileRecordService;

    @ApiOperation(value = "获取文件信息", httpMethod = "GET")
    @GetMapping("/getFileById/{fileId}")
    @ResponseBody
    public ResultModel getFileById(@PathVariable int fileId, ResultModel resultModel) {
        FileRecord fileRecord = fileRecordService.get(fileId);
        resultModel.setData(fileRecord);
        resultModel.info("获取成功");
        return resultModel;
    }

    @ApiOperation(value = "下载文件", httpMethod = "GET")
    @GetMapping("/getFileContentById/{fileId}")
    public ResponseEntity<byte[]> getFileContentById(@PathVariable int fileId) {
        FileRecord fileRecord = fileRecordService.get(fileId);
        // 创建文件
        File file = new File(fileRecord.getFilePath());
        // 获取文件名称
        String fileName = file.getName();
        // http头信息
        HttpHeaders headers = new HttpHeaders();
        // 设置编码
        String charsets = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        headers.setContentDispositionFormData("attachment", charsets);
        // 设置内容类型（MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息）
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ResponseEntity<byte[]> responseEntity = null;
        try {
            responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

}
